package Server    public class CPacketHandler    {        public static double NumProcess = 0;        public static double TimeProcess = 0;         // Receive Packet        public void OnReceive(CClient Client, CPacket Packet)        {            DateTime BeforeTime = DateTime.Now;	        int Id = Packet.GetId();            string Name = (Client.UserName == "")?("Slot " + Client.ClientId):Client.UserName;            if (Id != CCommon.MT_HEART_BEAT)            {                CLog.Trace("Receive " + CCommon.GetPacketName(Id) + " From <" + Name + "> Length=" + Packet.Length);            }            switch (Id)	        {	        case CCommon.MT_HEART_BEAT:		        break;            case CCommon.MT_BROADCAST:                CGlobal.Server.Active = false;                break;            case CCommon.MT_LOBBY_CHAT:                ProcessLobbyChat(Client, Packet);                break;            case CCommon.MT_LOGIN:		        ProcessLogin(Client, Packet);		        break;	        case CCommon.MT_REQUEST_REGISTER:		        ProcessRegister(Client, Packet);		        break;	        case CCommon.MT_REQUEST_SUB_CHANNEL_INFO:		        ProcessChannelInfo(Client, Packet);		        break;	        case CCommon.MT_REQUEST_LOBBY_INFO:		        ProcessLobbyInfo(Client, Packet);		        break;	        case CCommon.MT_CREATE_GAME:		        ProcessCreateGame(Client, Packet);		        break;	        case CCommon.MT_JOIN_GAME:		        ProcessJoinGame(Client, Packet);		        break;	        case CCommon.MT_REQUEST_AUTO_JOIN_GAME:		        ProcessAutoJoinGame(Client, Packet);		        break;	        case CCommon.MT_QUIT_GAME:		        ProcessQuitGame(Client, Packet);		        break;	        case CCommon.MT_REQUEST_USER_BASIC_INFO:		        ProcessUserBasicInfo(Client, Packet);		        break;	        case CCommon.MT_UPDATE_USER_BASIC_INFO:		        ProcessUpdateUserBasicInfo(Client, Packet);		        break;	        case CCommon.MT_REQUEST_USER_DETAIL_INFO:		        ProcessUserDetailInfo(Client, Packet);		        break;	        case CCommon.MT_REQUEST_USER_LIST:		        ProcessUserList(Client, Packet);		        break;            case CCommon.MT_REQUEST_ADD_FRIEND:                ProcessAddFriend(Client, Packet);                break;            case CCommon.MT_ACCEPT_ADD_FRIEND:                ProcessAcceptAddFriend(Client, Packet);                break;            case CCommon.MT_REQUEST_MAIL_LIST:		        ProcessMailList(Client, Packet);		        break;	        case CCommon.MT_REQUEST_MAIL_CONTENT:		        ProcessMailContent(Client, Packet);		        break;	        case CCommon.MT_REQUEST_SEND_MAIL:		        ProcessSendMail(Client, Packet);		        break;	        case CCommon.MT_REQUEST_DELETE_MAIL:		        ProcessDeleteMail(Client, Packet);		        break;	        case CCommon.MT_REQUEST_BUY_AVATAR:		        ProcessBuyAvatar(Client, Packet);		        break;	        case CCommon.MT_REQUEST_GIFT_DAILY_INFO:		        ProcessGiftDailyInfo(Client, Packet);		        break;	        case CCommon.MT_REQUEST_GIFT_TIME_INFO:		        ProcessGiftTimeInfo(Client, Packet);		        break;	        case CCommon.MT_REQUEST_RECEIVE_GIFT_DAILY:		        ProcessReceiveGiftDaily(Client, Packet);		        break;	        case CCommon.MT_REQUEST_RECEIVE_GIFT_TIME:		        ProcessReceiveGiftTime(Client, Packet);		        break;	        case CCommon.MT_REQUEST_INVITE:		        ProcessInvite(Client, Packet);		        break;	        case CCommon.MT_GAME_CHAT:		        ProcessGameChat(Client, Packet);		        break;	        case CCommon.MT_KICK:		        ProcessKick(Client, Packet);		        break;	        case CCommon.MT_START_GAME:		        ProcessStartGame(Client, Packet);		        break;	        case CCommon.MT_CHANGE_RULE:		        ProcessChangeRule(Client, Packet);		        break;            case CCommon.MT_REQUEST_PAYMENT:                ProcessRequestPayment(Client, Packet);                break;            case CCommon.MT_REQUEST_CHANGE_PASS:                ProcessRequestChangePass(Client, Packet);                break;            case CCommon.MT_SET_CHICKEN:                ProcessSetChicken(Client, Packet);                break;            case CCommon.MT_REQUEST_EXCHANGE_MONEY:                ProcessRequestExchangeMoney(Client, Packet);                break;            case CCommon.MT_LUCKY_NUMBER:                ProcessLuckyNumber(Client, Packet);                break;            case CCommon.MT_SELL_ITEM:                ProcessSellItem(Client, Packet);                break;            case CCommon.MT_MARKET_ITEM_LIST:                ProcessMarketItemList(Client, Packet);                break;            case CCommon.MT_BUY_ITEM:                ProcessBuyItem(Client, Packet);                break;            case CCommon.MT_USER_INFO:                ProcessUserInfo(Client, Packet);                break;            case CCommon.MT_SHOP_ITEM_LIST:                ProcessShopItemList(Client, Packet);                break;            case CCommon.MT_ASSET_LIST:                ProcessAssetList(Client, Packet);                break;            case CCommon.MT_CHANGE_AVATAR:                ProcessChangeAvatar(Client, Packet);                break;            case CCommon.MT_REMOVE_ASSET:                ProcessRemoveAsset(Client, Packet);                break;            case CCommon.MT_MY_MARKET_ITEM:                ProcessMyMarketItem(Client, Packet);                break;            case CCommon.MT_CANCEL_SELL_ITEM:                ProcessCancelSellItem(Client, Packet);                break;            case CCommon.MT_BUY_CARD:                ProcessBuyCard(Client, Packet);                break;            case CCommon.MT_LOCK_TABLE:                ProcessLockTable(Client, Packet);                break;            case CCommon.MT_SEND_AVATAR:                ProcessSendAvatar(Client, Packet);                break;            default:		        ProcessGamePacket(Client, Packet);		        break;	        }            DateTime AfterTime = DateTime.Now;            if (Id != CCommon.MT_HEART_BEAT)            {                double dt = AfterTime.Subtract(BeforeTime).TotalMilliseconds;                TimeProcess += dt;                NumProcess++;                CLog.Trace("## ProcessTime= " + (int)dt + "ms");            }        }        public void ProcessLockTable(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            // Get Channel Info            int ChannelId = Packet.ReadIntAt(0);            CChannel Channel = CGlobal.Server.GetChannel(ChannelId);            if (Channel == null)            {                return;            }            CTable Table = CGlobal.Server.FindAvailTable(Channel, Client.GetGold());            if (Table == null)            {                CPacket Packet1 = new CPacket(CCommon.MT_NOTIFY_ERROR);                Packet1.WriteInt(1);                Client.Send(Packet1);                return;            }            if (Table.GetNumClient() > 0)            {                CPacket p = new CPacket(CCommon.MT_JOIN_GAME_RESULT);                p.WriteInt(0);                p.WriteInt(Table.AppId);                p.WriteInt(Table.Channel.ChannelId);                p.WriteInt(Table.GameId);                p.WriteInt(1);                p.WriteInt(Table.GameStage);                p.WriteInt(0);                p.WriteDouble(Table.GoldBet);                Client.Send(p);                int Chair = Table.AddClient(Client);                Client.Chair = Chair;                Client.JoinTable(Table);            }            else            {                // Create Game                double GoldBet = Table.GetMinGoldBet();                Table.CreateGame(GoldBet);                int Chair = Table.AddClient(Client);                Client.JoinTable(Table);                Table.SetOwner(Client);                Client.Chair = Chair;                CUserGame UserGame = Client.GetUserGame(Table.AppId);                if (UserGame != null)                {                    Client.Level = UserGame.Level;                }                // Send Result                CPacket p = new CPacket(CCommon.MT_CREATE_GAME_RESULT);                p.WriteInt(0);                p.WriteInt(Table.AppId);                p.WriteInt(Table.Channel.ChannelId);                p.WriteInt(Table.GameId);                p.WriteInt(0);                p.WriteDouble(GoldBet);                Client.Send(p);            }            // Send Client Info            Table.SendClientJoin(Client);	        }        // Mua thẻ        public void ProcessBuyCard(CClient Client, CPacket Packet)        {            // Kiểm tra client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            // Lấy thông tin thẻ cào            int CardType = Packet.ReadIntAt(0);            int CardValue = Packet.ReadInt();            string PhoneNumber = Packet.ReadString(CCommon.MAX_MOBILE_NUMBER_LENGTH);            // Kiểm tra tiền có đủ để mua thẻ hay không?            double Cost = 10000000;            switch (CardValue)            {                case 50:                    Cost = 150000;                    break;                case 100:                    Cost = 300000;                    break;                case 200:                    Cost = 600000;                    break;            }            if (Client.GetXu() < Cost)            {                return;            }            // Trừ xu            Client.AddXu(-Cost);            Client.SaveXu();            // BUY_CARD		4. Mua thẻ cào ( giảm )            CLog.LogMoney("BUY_CARD", Client.UserName, Client.GetXu(), Client.GetGold(), -Cost, 0);            // Lưu thẻ vào DB            CSQL.SaveData("insert into CardBuying(UserName, CardType, CardValue, Time, PhoneNumber) values('"+Client.UserName+"',"+CardType+","+CardValue+",GETDATE(), '"+PhoneNumber+"')");            // Gửi mail thông báo cho người chơi            DateTime Now = DateTime.Now;            string Time = Now.Hour + ":" + Now.Minute + ":" + Now.Second;            string Date = Now.Day + "/" + Now.Month + "/" + Now.Year;            DateTime Today = new DateTime(Now.Year, Now.Month, Now.Day, 12, 0, 0);            string DatePay = "";            if (Now < Today)            {                DateTime d1 = Now;                DatePay = d1.Day + "/" + d1.Month + "/" + d1.Year;            }            else            {                DateTime d1;                if (Today.DayOfWeek.Equals("Friday"))                {                    d1 = Now.AddDays(3);                                }                else                {                    d1 = Now.AddDays(1);                                }                DatePay = d1.Day + "/" + d1.Month + "/" + d1.Year;            }            CGlobal.Database.SendMail(Client.AccountId, "admin", Client.UserName, "Mua the cao", "Ban da mua ma the "+CCommon.GetCardTypeName(CardType)+" voi menh gia "+CardValue+"K vao luc "+Time+" ngay "+Date+". He thong se kiem tra va gui vao luc 16h ngay "+DatePay+".");            // Trả kết quả            CPacket p = new CPacket(CCommon.MT_BUY_CARD);            p.WriteDouble(Client.GetGold());            p.WriteDouble(Client.GetXu());            Client.Send(p);        }        // Hủy rao bán vật phẩm        public void ProcessCancelSellItem(CClient Client, CPacket Packet)        {            // Kiểm tra client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            // Lấy thông tin vật phẩm            int MarketId = Packet.ReadIntAt(0);            DataTable dt = CSQL.GetData("select * from Market where Id=" + MarketId + " and UserName='"+Client.UserName+"'");            if (dt.Rows.Count == 0)            {                return;            }            int ItemType = Convert.ToInt32(dt.Rows[0]["ItemType"].ToString());            int ItemId = Convert.ToInt32(dt.Rows[0]["ItemId"].ToString());            double ItemAmount = CCommon.String2Double(dt.Rows[0]["ItemAmount"].ToString());            switch (ItemType)            {                 // Trả lại vàng cho người chơi                case CCommon.ITEM_GOLD:                    Client.AddGold(ItemAmount, "Huy rao ban vat pham");                    Client.SaveGold();                    break;                // Trả lại xu cho người chơi                case CCommon.ITEM_XU:                    Client.AddXu(ItemAmount);                    Client.SaveXu();                    break;                    // Trả lại vật phẩm cho người chơi                default:                    CSQL.SaveData("insert into UserAsset(UserName, ItemId) values ('"+Client.UserName+"',"+ItemId+")");                    break;            }            // Xóa item khỏi chợ            CSQL.SaveData("delete from Market where Id=" + MarketId);            // Trả kết quả            int ErrorId = 0;            CPacket p = new CPacket(CCommon.MT_CANCEL_SELL_ITEM);            p.WriteInt(ErrorId);            p.WriteDouble(Client.GetGold());            p.WriteDouble(Client.GetXu());            p.WriteInt(MarketId);            Client.Send(p);        }        // Thanh lý tài sản        public void ProcessRemoveAsset(CClient Client, CPacket Packet)        {            // Kiểm tra client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            int Result = 1;            int AssetId = Packet.ReadIntAt(0);            DataTable dt = CSQL.GetData("select * from UserAsset,ShopItem where UserAsset.Id=" + AssetId + " and UserName='" + Client.UserName + "' and UserAsset.ItemId=ShopItem.Id");            if (dt.Rows.Count > 0 && Result == 0)            {                // Lấy thông tin vật phẩm                DataTable dt1 = CSQL.GetData("select * from ShopItem where Id="+dt.Rows[0]["ItemId"].ToString());                if (dt1.Rows.Count > 0)                {                    int Currency = Convert.ToInt32(dt1.Rows[0]["Currency"].ToString());                    double Cost = CCommon.String2Double(dt1.Rows[0]["Cost"].ToString());                    int Type = CCommon.String2Int(dt1.Rows[0]["Type"].ToString());                    int ImageId = CCommon.String2Int(dt1.Rows[0]["ImageId"].ToString());                    double GoldAdd = 0;                    double XuAdd = 0;                    // Không thanh lý được avatar đang sử dụng                    if (Type == CCommon.ITEM_AVATAR || Type == CCommon.ITEM_FULL_AVATAR)                    {                        if (Client.AvatarId == ImageId)                        {                            Result = 2;                        }                    }                    // Cộng tiền sau khi thanh lý                    if (Result == 0)                    {                        switch (Currency)                        {                            case CCommon.CURRENCY_GOLD:                                GoldAdd = Cost / 2;                                Client.AddGold(Cost / 2, "Xoa tai san");                                Client.SaveGold();                                break;                            case CCommon.CURRENCY_XU:                                GoldAdd = Cost * 5;                                Client.AddGold(Cost * 5, "Xoa tai san");                                Client.SaveGold();                                break;                        }                        // REMOVE_ASSET		2. Thanh lý tài sản ( Tăng )                        CLog.LogMoney("REMOVE_ASSET", Client.UserName, Client.GetXu(), Client.GetGold(), XuAdd, GoldAdd);                    }                }                // Xóa tài sản                if (Result == 0)                {                    CSQL.SaveData("delete UserAsset where Id=" + AssetId);                }            }            else            {                Result = 1;            }            CPacket p = new CPacket(CCommon.MT_REMOVE_ASSET);            p.WriteInt(Result);            p.WriteDouble(Client.GetGold());            p.WriteDouble(Client.GetXu());            Client.Send(p);        }        // Lấy danh sách tài sản của người chơi        public void ProcessChangeAvatar(CClient Client, CPacket Packet)        {            // Kiểm tra client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            int AssetId = Packet.ReadIntAt(0);            int AvatarId = Packet.ReadInt();            Client.AvatarId = AvatarId;            string Query1 = "update UserAsset set Active=0 where UserName='" + Client.UserName + "' and Id<>" + AssetId;            string Query2 = "update UserAsset set Active=1 where UserName='" + Client.UserName + "' and Id=" + AssetId;            CSQL.SaveData(Query1);            CSQL.SaveData(Query2);        }        // Lấy danh sách tài sản của người chơi        public void ProcessAssetList(CClient Client, CPacket Packet)        {            // Kiểm tra client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            // Truy vấn từ CSDL            DataTable dt = CSQL.GetData("select UserAsset.Id, UserAsset.UserName, UserAsset.ItemId,ShopItem.Name,ShopItem.Type,ShopItem.ImageId,ShopItem.Cost,ShopItem.Currency from UserAsset, ShopItem where UserName='" + Client.UserName + "' and UserAsset.ItemId=ShopItem.Id and (Type=3 or Type = 4)");            // Gửi kết quả            CPacket p = new CPacket(CCommon.MT_ASSET_LIST);            p.WriteInt(dt.Rows.Count);            for (int i = 0; i < dt.Rows.Count; i++)            {                int Id = Convert.ToInt32(dt.Rows[i]["Id"]);                int ItemId = Convert.ToInt32(dt.Rows[i]["ItemId"]);                int Type = Convert.ToInt32(dt.Rows[i]["Type"]);                string Name = dt.Rows[i]["Name"].ToString();                int ImageId = Convert.ToInt32(dt.Rows[i]["ImageId"]);                double Cost = CCommon.String2Double(dt.Rows[i]["Cost"].ToString());                int Currency = Convert.ToInt32(dt.Rows[i]["Currency"].ToString());                p.WriteInt(Id);                p.WriteInt(ItemId);                p.WriteInt(Type);                p.WriteString(Name, CCommon.MAX_ITEM_NAME_LENGTH);                p.WriteInt(ImageId);                p.WriteDouble(Cost);                p.WriteInt(Currency);            }            Client.Send(p);        }        // Lấy danh sách các items trong shop        public void ProcessShopItemList(CClient Client, CPacket Packet)        {            // Kiểm tra client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }                        // Lấy kiểm item            int Type = Packet.ReadIntAt(0);            // Truy vấn từ CSDL            DataTable dt = CSQL.GetData("select * from ShopItem where Type="+Type + " order by ItemIndex asc");             // Gửi kết quả            CPacket p = new CPacket(CCommon.MT_SHOP_ITEM_LIST);            p.WriteInt(Type);            p.WriteInt(dt.Rows.Count);            for(int i = 0; i < dt.Rows.Count; i ++)            {                int Id = Convert.ToInt32(dt.Rows[i]["Id"]);                string Name = dt.Rows[i]["Name"].ToString();                int ImageId = Convert.ToInt32(dt.Rows[i]["ImageId"]);                double Cost = CCommon.String2Double(dt.Rows[i]["Cost"].ToString());                int Currency = Convert.ToInt32(dt.Rows[i]["Currency"].ToString());                p.WriteByte((byte)Id);                p.WriteString(Name, CCommon.MAX_ITEM_NAME_LENGTH);                p.WriteByte((byte)ImageId);                p.WriteInt((int)Cost);                p.WriteByte((byte)Currency);            }            Client.Send(p);        }        // Xem thông tin người chơi        public void ProcessUserInfo(CClient Client, CPacket Packet)        {            // Kiểm tra client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            // Lấy thông tin người chơi            string UserName = Packet.ReadStringAt(0, CCommon.MAX_USERNAME_LENGTH);            DataTable dt = CSQL.GetData("select * from TableUser where UserName='"+UserName+"'");            if (dt.Rows.Count == 0)            {                return;            }            int AvatarId = Convert.ToInt32(dt.Rows[0]["AvatarId"].ToString());            double Gold = CCommon.String2Double(dt.Rows[0]["VKim"].ToString());            double Xu = CCommon.String2Double(dt.Rows[0]["Xu"].ToString());            int Gender = CCommon.String2Int(dt.Rows[0]["Sex"].ToString());            string RealName = dt.Rows[0]["RealName"].ToString();            string Blast = dt.Rows[0]["Status"].ToString();            // Gửi kết quả            CPacket p = new CPacket(CCommon.MT_USER_INFO);            p.WriteString(UserName, CCommon.MAX_USERNAME_LENGTH);            p.WriteInt(AvatarId);            p.WriteDouble(Gold);            p.WriteDouble(Xu);            p.WriteInt(Gender);            p.WriteString(RealName, CCommon.MAX_USERNAME_LENGTH);            p.WriteString(Blast, CCommon.MAX_STATUS_LENGTH);            Client.Send(p);        }        // Mua đồ trong chợ        public void ProcessBuyItem(CClient Client, CPacket Packet)        {            return;            //// Kiểm tra client            //if (!Client.IsLogin() || Client.IsInTable())            //{            //    return;            //}            //int ErrorId = 0;            //// Lấy thông tin vật phẩm            //int MarketId = Packet.ReadIntAt(0);            //DataTable dt = CSQL.GetData("select * from Market where Id=" + MarketId);            //if (dt.Rows.Count == 0)            //{            //    ErrorId = 1;            //}            //if (ErrorId == 0)            //{            //    int ItemId = Convert.ToInt32(dt.Rows[0]["ItemId"]);            //    int ItemType = Convert.ToInt32(dt.Rows[0]["ItemType"]);            //    int ItemAmount = Convert.ToInt32(dt.Rows[0]["ItemAmount"]);            //    int Currency = Convert.ToInt32(dt.Rows[0]["Currency"]);            //    double Cost = CCommon.String2Double(dt.Rows[0]["ItemCost"].ToString());            //    double GoldAdd = 0;            //    double XuAdd = 0;            //    double XuTax = 0;            //    double GoldTax = 0;            //    // Trừ tiền của người mua            //    switch (Currency)            //    {            //        case CCommon.CURRENCY_GOLD:            //            Client.AddGold(-Cost, "Mua vat pham");            //            Client.SaveGold();            //            break;            //        case CCommon.CURRENCY_XU:            //            Client.AddXu(-Cost);            //            Client.SaveXu();            //            break;            //    }            //    // Cộng tiền cho người bán            //    CTableUser Seller = CGlobal.Cache.GetTableUser(dt.Rows[0]["UserName"].ToString());            //    string Action = "SELL_MARKET_ITEM";            //    switch (ItemType)            //    {            //        case CCommon.ITEM_GOLD:            //            Action = "SELL_GOLD";            //            break;            //        case CCommon.ITEM_XU:            //            Action = "SELL_XU";            //            break;            //    }            //    switch (Currency)            //    {            //        case CCommon.CURRENCY_GOLD:            //            if (Seller != null)            //            {            //                Seller.AddGold(Cost * 0.95, true);            //                CLog.LogMoney(Action, Seller.UserName, Seller.GetXu(), Seller.GetGold(), -ItemAmount, Cost * 0.95);            //                // Lưu log giao dịch            //                CLog.LogBuyMarketItem(Seller.UserName, -ItemAmount, Cost * 0.95, 0, Cost * 0.05, Seller.GetXu(), Seller.GetGold());            //            }            //            break;            //        case CCommon.CURRENCY_XU:            //            if (Seller != null)            //            {            //                Seller.AddXu(Cost * 0.95, true);            //                CLog.LogMoney(Action, Seller.UserName, Seller.GetXu(), Seller.GetGold(), Cost * 0.95, -ItemAmount);            //                // Lưu log giao dịch            //                CLog.LogBuyMarketItem(Seller.UserName, Cost * 0.95, - ItemAmount, Cost * 0.05, 0, Seller.GetXu(), Seller.GetGold());            //            }            //            break;            //    }            //    switch(ItemType)            //    {            //        case CCommon.ITEM_GOLD:            //            {            //                // Thêm gold cho người mua (trừ thuế)            //                GoldAdd = ItemAmount * 0.95;            //                GoldTax = ItemAmount * 0.05;            //                Client.AddGold(GoldAdd, "Mua vat pham");            //                Client.SaveGold();            //                CGlobal.Database.SendMail(Seller.Id, "admin", Seller.UserName, "Giao dich thanh cong!", "Ban da ban thanh cong " + ItemAmount + "$ voi gia " + Math.Round(Cost, 0) + "Xu tren cho, so tien ban nhan duoc sau khi tru thue la " + Math.Round((Cost * 0.95), 0) + "Xu");            //                // BUY_GOLD		3. Mua vật phẩm trong chợ (Giảm)            //                CLog.LogMoney("BUY_GOLD", Client.UserName, Client.GetXu(), Client.GetGold(), -Cost, GoldAdd);            //            }            //            break;            //        case CCommon.ITEM_XU:            //            {            //                // Thêm xu cho người mua (trừ thuế)            //                XuAdd = ItemAmount * 0.95;            //                XuTax = ItemAmount * 0.05;            //                Client.AddXu(XuAdd);            //                Client.SaveXu();            //                CGlobal.Database.SendMail(Seller.Id, "admin", Seller.UserName, "Giao dich thanh cong!", "Ban da ban thanh cong " + ItemAmount + "Xu voi gia " + Math.Round(Cost, 0) + "$ tren cho, so tien ban nhan duoc sau khi tru thue la " + Math.Round((Cost * 0.95), 0) + "$");            //                // BUY_XU			3. Mua vật phẩm trong chợ (Giảm)            //                CLog.LogMoney("BUY_XU", Client.UserName, Client.GetXu(), Client.GetGold(), XuAdd, -Cost);            //            }            //            break;            //        default:            //            // Thêm đồ vào tài sản của người chơi            //            DataTable dt1 = CSQL.GetData("select * from ShopItem where Id=" + ItemId);            //            if (dt1.Rows.Count > 0)            //            {            //                string ItemName = dt1.Rows[0]["Name"].ToString();            //                int ImageId = Convert.ToInt32(dt1.Rows[0]["ImageId"].ToString());            //                CSQL.SaveData("insert into UserAsset(UserName, ItemId) " +            //                    "values('" + Client.UserName + "'," + ItemId + ")");            //                CGlobal.Database.SendMail(Seller.Id, "admin", Seller.UserName, "Giao dich thanh cong!",             //                    "Ban da ban thanh cong vat pham " + ItemName +             //                    " voi gia " + Math.Round(Cost, 0) + "$ tren cho, "+            //                    "so tien ban nhan duoc sau khi tru thue la " + Math.Round((Cost * 0.95), 0) + "$");            //            }            //            // BUY_MARKET_ITEM	3. Mua vật phẩm trong chợ (Giảm)            //            switch (Currency)            //            {            //                case CCommon.CURRENCY_GOLD:            //                    CLog.LogMoney("BUY_MARKET_ITEM", Client.UserName, Client.GetXu(), Client.GetGold(), 0, -Cost);            //                    break;            //                case CCommon.CURRENCY_XU:            //                    CLog.LogMoney("BUY_MARKET_ITEM", Client.UserName, Client.GetXu(), Client.GetGold(), -Cost, 0);            //                    break;            //            }            //            break;            //    }            //    // Nếu người bán online, gửi gói tin update tiền về cho người bán            //    if (Seller != null)            //    {            //        CClient ClientSeller = CGlobal.Server.GetClientByAccountId(Seller.Id);            //        if (ClientSeller != null && ClientSeller.IsLogin())            //        {            //            ClientSeller.SetGold(Seller.GetGold());            //            ClientSeller.SetXu(Seller.GetXu());            //            CPacket p1 = new CPacket(CCommon.MT_NEW_MONEY);            //            p1.WriteDouble(ClientSeller.GetGold());            //            p1.WriteDouble(ClientSeller.GetXu());            //            ClientSeller.Send(p1);            //        }            //    }            //    // Xóa đồ trong chợ            //    CSQL.SaveData("delete from Market where Id=" + MarketId);            //    // Lưu log giao dịch            //    CLog.LogBuyMarketItem(Client.UserName, XuAdd, GoldAdd, XuTax, GoldTax, Client.GetXu(), Client.GetGold());            //}                        //// Trả kết quả            //CPacket p = new CPacket(CCommon.MT_BUY_ITEM);            //p.WriteInt(ErrorId);            //p.WriteInt(MarketId);            //p.WriteDouble(Client.GetGold());            //p.WriteDouble(Client.GetXu());            //Client.Send(p);        }        // Lấy danh các vật phẩm đã rao bán        public void ProcessMyMarketItem(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            // Lấy dữ liệu từ DB            DataTable dt = CSQL.GetData("select top 10 * from Market where UserName='"+Client.UserName+"' order by Time desc");            // Trả kết quả            CPacket p = new CPacket(CCommon.MT_MY_MARKET_ITEM);            p.WriteInt(dt.Rows.Count);            for (int i = 0; i < dt.Rows.Count; i++)            {                int MarketId = Convert.ToInt32(dt.Rows[i]["Id"].ToString());                int ItemId = Convert.ToInt32(dt.Rows[i]["ItemId"].ToString());                int ItemType = Convert.ToInt32(dt.Rows[i]["ItemType"].ToString());                double Amount = CCommon.String2Double(dt.Rows[i]["ItemAmount"].ToString());                double Cost = CCommon.String2Double(dt.Rows[i]["ItemCost"].ToString());                int Currency = Convert.ToInt32(dt.Rows[i]["Currency"].ToString());                string UserName = dt.Rows[i]["UserName"].ToString();                string ItemName = "";                int ImageId = 0;                if (ItemId != -1)                {                    DataTable dt2 = CSQL.GetData("select * from ShopItem where Id=" + ItemId);                    if (dt2.Rows.Count > 0)                    {                        ItemName = dt2.Rows[0]["Name"].ToString();                        ImageId = CCommon.String2Int(dt2.Rows[0]["ImageId"].ToString());                    }                }                p.WriteInt(MarketId);                p.WriteInt(ItemId);                p.WriteInt(ItemType);                p.WriteDouble(Amount);                p.WriteDouble(Cost);                p.WriteInt(Currency);                p.WriteString(UserName, CCommon.MAX_USERNAME_LENGTH);                p.WriteString(ItemName, CCommon.MAX_ITEM_NAME_LENGTH);                p.WriteInt(ImageId);            }            Client.Send(p);                    }        // Lấy danh sách đồ trong chợ đen        public void ProcessMarketItemList(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            // Kiểm tra những item hết hạn trong chợ và hoàn lại tiền cho người rao bán            DataTable dt1 = CSQL.GetData("select * from Market");            for (int i = 0; i < dt1.Rows.Count; i++)            {                string Time = dt1.Rows[i]["Time"].ToString();                DateTime t = new DateTime();                DateTime.TryParse(Time, out t);                TimeSpan d = DateTime.Now.Subtract(t);                if (d.TotalHours > 24)                {                    int MarketId = Convert.ToInt32(dt1.Rows[i]["Id"].ToString());                    int ItemType = Convert.ToInt32(dt1.Rows[i]["ItemType"].ToString());                    int ItemId = Convert.ToInt32(dt1.Rows[i]["ItemId"].ToString());                    int Currency = Convert.ToInt32(dt1.Rows[i]["Currency"].ToString());                    double ItemAmount = CCommon.String2Double(dt1.Rows[i]["ItemAmount"].ToString());                    double ItemCost = CCommon.String2Double(dt1.Rows[i]["ItemCost"].ToString());                    string UserName = dt1.Rows[i]["UserName"].ToString();                    CClient cl = CGlobal.Server.GetClientByUserName(UserName);                    switch (ItemType)                    {                        case CCommon.ITEM_GOLD:                            if (cl != null)                            {                                cl.AddGold(ItemAmount, "Hoan tien cho nguoi ban");                                cl.SaveGold();                            }                            break;                        case CCommon.ITEM_XU:                            if (cl != null)                            {                                cl.AddXu(ItemAmount);                                cl.SaveXu();                            }                            break;                    }                    CSQL.SaveData("delete from Market where Id="+MarketId);                }            }            // Kiểu đồ            int Type = Packet.ReadIntAt(0);            // Lấy dữ liệu từ DB            string Query = "select top 10 * from Market where ItemType=" + Type + " order by Time desc";            if (Type != CCommon.ITEM_GOLD && Type != CCommon.ITEM_XU)            {                Query = "select top 10 * from Market where ItemType<>"+CCommon.ITEM_GOLD+" and ItemType<>"+CCommon.ITEM_XU+" order by Time desc";                        }            DataTable dt = CSQL.GetData(Query);             // Trả kết quả            CPacket p = new CPacket(CCommon.MT_MARKET_ITEM_LIST);            p.WriteInt(Type);            p.WriteInt(dt.Rows.Count);            for (int i = 0; i < dt.Rows.Count; i++)            {                int MarketId = Convert.ToInt32(dt.Rows[i]["Id"].ToString());                int ItemId = Convert.ToInt32(dt.Rows[i]["ItemId"].ToString());                double Amount = CCommon.String2Double(dt.Rows[i]["ItemAmount"].ToString());                double Cost = CCommon.String2Double(dt.Rows[i]["ItemCost"].ToString());                int Currency = Convert.ToInt32(dt.Rows[i]["Currency"].ToString());                string UserName = dt.Rows[i]["UserName"].ToString();                string ItemName = "";                int ImageId = 0;                if (ItemId != -1)                {                    DataTable dt2 = CSQL.GetData("select * from ShopItem where Id="+ItemId);                    if (dt2.Rows.Count > 0)                    {                        ItemName = dt2.Rows[0]["Name"].ToString();                        ImageId = CCommon.String2Int(dt2.Rows[0]["ImageId"].ToString());                    }                }                p.WriteInt(MarketId);                p.WriteInt(ItemId);                p.WriteDouble(Amount);                p.WriteDouble(Cost);                p.WriteInt(Currency);                p.WriteString(UserName, CCommon.MAX_USERNAME_LENGTH);                p.WriteString(ItemName, CCommon.MAX_ITEM_NAME_LENGTH);                p.WriteInt(ImageId);            }            Client.Send(p);        }        // Rao bán đồ trên chợ đen        public void ProcessSellItem(CClient Client, CPacket Packet)        {            return;            //int ErrorId = 0;            //// Check Client            //if (!Client.IsLogin() || Client.IsInTable())            //{            //    return;            //}            //// Kiểm tra số lần rao bán            //int Num = 0;            //DataTable dt = CSQL.GetData("select count(*) as Num from Market where UserName='"+Client.UserName+"'");            //if (dt.Rows.Count == 1)            //{            //    int.TryParse(dt.Rows[0]["Num"].ToString(), out Num);            //}            //if (Num >= 3)            //{            //    ErrorId = 1;            //}            //// Đọc dữ liệu            //int Type = Packet.ReadIntAt(0);            //double Amount = Packet.ReadDouble();            //double Cost = Packet.ReadDouble();            //int Currency = Packet.ReadInt();            //int ItemId = Packet.ReadInt();            //// Bán gold            //if (Type == CCommon.ITEM_GOLD)            //{            //    if (Cost < 15000)            //    {            //        return;            //    }            //}            //DataTable dt1 = CSQL.GetData("select * from ShopItem where Id="+ItemId);            //if (dt1.Rows.Count > 0)            //{            //    int ItemCurrency = Convert.ToInt32(dt1.Rows[0]["Currency"].ToString());                            //    // Vật phẩm rao bằng $ không thể rao bán            //    if (ItemCurrency == CCommon.CURRENCY_GOLD)            //    {            //        ErrorId = 2;            //    }            //}            //// Kiểm tra vật phẩm đang sử dụng không thể rao bán            //DataTable dt2 = CSQL.GetData("select * from UserAsset where UserName='"+Client.UserName+"' and ItemId=" + ItemId + " and Active=1");            //if (dt2.Rows.Count > 0)            //{            //    ErrorId = 3;            //}            //// Xử lý            //if (ErrorId == 0)            //{            //    // Trừ phí giao dịch            //    Client.AddGold(-5000, "Tru phi giao dich");            //    //MARKET_FEE		8. Phí rao bán vật phẩm 24h trên chợ ( Giảm 5.000)            //    CLog.LogMoney("MARKET_FEE", Client.UserName, Client.GetXu(), Client.GetGold(), 0, -5000);            //    // Trừ vàng/xu nếu bán vàng/xu            //    switch (Type)            //    {            //        case CCommon.ITEM_GOLD:            //            Client.AddGold(-Amount, "Ban vat pham");            //            break;            //        case CCommon.ITEM_XU:            //            Client.AddXu(-Amount);            //            break;            //    }            //    // Xóa vật phẩm trong tài sản nếu bán vật phẩm            //    if (ItemId != -1)            //    {            //        CSQL.SaveData("delete from UserAsset where UserName='"+Client.UserName+"' and ItemId="+ItemId);            //    }                            //    // Insert vào DB            //    CSQL.SaveData("insert into Market(UserName,ItemType,ItemAmount,ItemCost,ItemId,Currency,Time) values(" +            //        "'" + Client.UserName + "'," + Type + "," + Amount + "," + Cost + "," + ItemId + "," + Currency + ",GETDATE())");            //    // Gửi thư cho người chơi            //    //CGlobal.Database.SendMail(Client.AccountId, "admin", Client.UserName, "Rao ban vat pham", "Vat pham ban rao ban se duoc luu o cho va duoc hoan lai khi ban huy ban hoac tin rao ban het han.");            //}            //// Gửi kết quả            //CPacket p = new CPacket(CCommon.MT_SELL_ITEM);            //p.WriteInt(ErrorId);            //p.WriteDouble(Client.GetGold());            //p.WriteDouble(Client.GetXu());            //p.WriteInt(ItemId);            //Client.Send(p);        }        // Tham gia event: Thần tài gõ cửa        private void ProcessLuckyNumber(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            // Kiểm tra tiền            if (Client.GetGold() < 100000)            {                return;            }            // Lấy số            int Number = Packet.ReadIntAt(0);            // Kiểm tra số hợp lệ            if (Number < 10 || Number > 99)            {                return;            }            // Lưu số            CSQL.SaveData("insert into LuckyNumber(UserName, Number, Time) values('"+Client.UserName+"',"+Number+",GETDATE())");            // Trừ tiền            Client.AddGold(-30000, "Tru tien lucky number");            Client.SaveGold();            // EVENT_NUMBER_FEE	15.Sự kiện thần gài gõ cửa ( -30.000/số)            CLog.LogMoney("EVENT_NUMBER_FEE", Client.UserName, Client.GetXu(), Client.GetGold(), 0, -30000);            // Gửi mail thông báo            DateTime Now = DateTime.Now;            if (Now.Hour > 18)            {                DateTime dt = new DateTime(Now.Year, Now.Month, Now.Day);                dt = dt.AddDays(1);                Now = dt;            }            CGlobal.Database.SendMail(Client.AccountId, "admin", Client.UserName, "Than tai go cua", "Ban da tham gia su kien: Than tai go cua ngay "+Now.Day+"/"+Now.Month+"/"+Now.Year+" bang cach dang ky so may man: "+Number+". Cong bo va trao giai thuong vao 10h sang ngay hom sau. Chuc ban may man!");            // Trả kết quả            CPacket p = new CPacket(CCommon.MT_LUCKY_NUMBER);            p.WriteInt(Number);            p.WriteDouble(Client.GetGold());            Client.Send(p);        }        // Đổi xu sang gold        private void ProcessRequestExchangeMoney(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            // Kiểm tra hợp lệ            double Xu = Packet.ReadDoubleAt(0);            if (Xu <= 0 || Xu > Client.GetXu())            {                return;            }            // Đổi xu            double Gold = Xu * 10;            Client.AddGold(Gold, "Doi xu");            Client.AddXu(-Xu);            Client.SaveMoney();            // Log            CLog.LogExchangeXu(Client.UserName, Xu, Gold, Client.GetXu(), Client.GetGold());                        // EXCHANGE_XU		7. Đổi Xu sang $ trong ngân hàng ( Tăng )            CLog.LogMoney("EXCHANGE_XU", Client.UserName, Client.GetXu(), Client.GetGold(), -Xu, Gold);            // Gửi kết quả            CPacket p = new CPacket(CCommon.MT_EXCHANGE_MONEY);            p.WriteDouble(Client.GetGold());            p.WriteDouble(Client.GetXu());            Client.Send(p);        }        // Lobby Chat        private void ProcessLobbyChat(CClient Client, CPacket Packet)        {            CGlobal.Server.BroadCast(Packet);        }        // Process Payment        public void ProcessRequestPayment(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            int CPID = Packet.ReadIntAt(0);            string Type = Packet.ReadString(3);            string Number = Packet.ReadString(CCommon.MAX_CARD_LENGTH);            int Result = 1;            double GoldAdd = 0;            Console.WriteLine("CPID: " + CPID);            Console.WriteLine("Card Type: " + Type);            Console.WriteLine("Card Number: " + Number);            string responseXML = CGapPay.DoGetRequest(Type, Number, Client.UserName, CPID);            if (!string.IsNullOrEmpty(responseXML))            {                Result = CGapPay.ProcessResult(responseXML, ref GoldAdd);                if (Result == 0)                {                    Client.AddGold(GoldAdd, "");                    Client.SaveGold();                }            }            else            {                Result = 1;                Console.WriteLine("Khong co ket qua tra ve cho yeu cau thanh toan.");            }            CPacket p = new CPacket(CCommon.MT_PAYMENT_RESULT);            p.WriteInt(Result);            p.WriteDouble(GoldAdd);            Client.Send(p);        }        // Process Change Password        public void ProcessRequestChangePass(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            string OldPass = Packet.ReadStringAt(0, CCommon.MAX_PASSWORD_LENGTH);            string NewPass = Packet.ReadString(CCommon.MAX_PASSWORD_LENGTH);            int Result = 0;            if (Client.Password.Equals(CCommon.MD5(OldPass)))            {                Client.Password = CCommon.MD5(NewPass);                CSQL.SaveData("update tableuser set Password='" + Client.Password + "' where Id=" + Client.AccountId);            }            else            {                Result = 1;            }            CPacket p = new CPacket(CCommon.MT_CHANGE_PASS_RESULT);            p.WriteInt(Result);            Client.Send(p);        }        // Process login        public void ProcessLogin(CClient Client, CPacket Packet)        {	        // Check Client Logined            if(Client.IsLogin())	        {		        CLog.Trace("Client " + Client.ClientId + " is logined\n");		        return;	        }	        // Get Request	        string UserName = Packet.ReadStringAt(0, CCommon.MAX_USERNAME_LENGTH);	        string Password = Packet.ReadString(CCommon.MAX_SESSION_LENGTH);            // Push Cache            DataTable dt = CSQL.GetData("select * from TableUser where UserName='" + UserName + "' and (Password='" + CCommon.MD5(Password) + "' or SessionId='" + Password + "')");        //    DataTable dt = CSQL.GetData("select * from TableUser");	        // Result            int Error = 0;	        CUserInfo UserInfo = new CUserInfo();            if (dt.Rows.Count == 0)            {                Error = 2;            }            else            {                // Lấy số lượng mail chưa đọc                int UnreadMail = 0;                DataTable dt2 = CSQL.GetData("select count(*) as UnreadMail from Mail where touserid=" + CCommon.String2Int(dt.Rows[0]["Id"].ToString()) + " and status=0");                if (dt2.Rows.Count > 0)                {                    UnreadMail = CCommon.String2Int(dt2.Rows[0]["UnreadMail"].ToString());                }                // Cập nhật last login                string LastLogin = dt.Rows[0]["LastLogin"].ToString();                if (LastLogin.Length == 0)                {                    Client.LastLogin = DateTime.Now.ToString();                    Client.ReceiveGift = 0;                    Client.DayCount = 1;                }                else                {                    int LastYear = 0, LastMonth = 0, LastDay = 0;                    CCommon.StringToDate(Client.LastLogin, ref LastYear, ref LastMonth, ref LastDay);                    DateTime Now = DateTime.Now;                    int OffsetDay = CCommon.GetOffsetDay(LastYear, LastMonth, LastDay, Now.Year, Now.Month, Now.Day);                    if (OffsetDay <= 0)                    {                        Client.LastLogin = Now.ToString();                    }                    else if (OffsetDay == 1)                    {                        Client.LastLogin = Now.ToString();                        Client.DayCount++;                        if (Client.DayCount > 5)                        {                            Client.DayCount = 1;                        }                        Client.ReceiveGift = 0;                        Client.GiftCount = 0;                    }                    else                    {                        Client.LastLogin = Now.ToString();                        Client.ReceiveGift = 0;                        Client.GiftCount = 0;                        Client.DayCount = 1;                    }                }                // Lấy giá trị trả về                UserInfo.UserId = Client.ClientId;                UserInfo.AccountId = CCommon.String2Int(dt.Rows[0]["Id"].ToString());                UserInfo.AvatarId = CCommon.String2Int(dt.Rows[0]["AvatarId"].ToString());                UserInfo.UnreadMail = 0;                UserInfo.Gold = CCommon.String2Double(dt.Rows[0]["VKim"].ToString());                UserInfo.UserName = dt.Rows[0]["UserName"].ToString();                UserInfo.UnreadMail = UnreadMail;                UserInfo.Xu = CCommon.String2Double(dt.Rows[0]["Xu"].ToString());                UserInfo.RealName = dt.Rows[0]["RealName"].ToString();                UserInfo.FirstLogin = CCommon.String2Int(dt.Rows[0]["FirstLogin"].ToString());                UserInfo.Active = CCommon.String2Int(dt.Rows[0]["Active"].ToString());                UserInfo.Lock = 0;                UserInfo.XuPay = CCommon.String2Double(dt.Rows[0]["XuPay"].ToString());                // Lưu thành tích                Client.ListUserGame.Clear();                DataTable dt3 = CSQL.GetData("select * from usergame where UserId=" + CCommon.String2Int(dt.Rows[0]["Id"].ToString()));                for (int i = 0; i < dt3.Rows.Count; i++)                {                    CUserGame UserGame = new CUserGame();                    int.TryParse(dt3.Rows[i]["GameId"].ToString(), out UserGame.GameId);                    int.TryParse(dt3.Rows[i]["Exp"].ToString(), out UserGame.Exp);                    int.TryParse(dt3.Rows[i]["Level"].ToString(), out UserGame.Level);                    int.TryParse(dt3.Rows[i]["Lost"].ToString(), out UserGame.Lost);                    int.TryParse(dt3.Rows[i]["Quit"].ToString(), out UserGame.Quit);                    int.TryParse(dt3.Rows[i]["Win"].ToString(), out UserGame.Win);                    Client.ListUserGame.Add(UserGame);                }                // Cập nhật tiền xu nạp                double GoldPay = CCommon.String2Double(dt.Rows[0]["GoldPay"].ToString());                double XuPay = CCommon.String2Double(dt.Rows[0]["XuPay"].ToString());                CSQL.SaveData("update TableUser set GoldPay=0,XuPay=0,VKim=" + (UserInfo.Gold + GoldPay) + ",Xu=" + (UserInfo.Xu + XuPay) + " where Id=" + CCommon.String2Int(dt.Rows[0]["Id"].ToString()));                // Cập nhật danh sách emotion vip                DataTable dt4 = CSQL.GetData("select UserAsset.Id, UserAsset.UserName, UserAsset.ItemId,ShopItem.Name,ShopItem.Type,ShopItem.ImageId,ShopItem.Cost,ShopItem.Currency from UserAsset, ShopItem where UserName='" + UserName + "' and UserAsset.ItemId=ShopItem.Id and Type = 5");                Client.EmotionList.Clear();                for (int i = 0; i < dt4.Rows.Count; i++)                {                    int ImageId = CCommon.String2Int(dt4.Rows[0]["ImageId"].ToString());                    Client.EmotionList.Add(ImageId);                }            }	        // Check Client Online	        CClient ClientOnline = CGlobal.Server.GetClientByAccountId(UserInfo.AccountId);            if (ClientOnline != null && !ClientOnline.IsBot)	        {		        Error = 1;                CGlobal.Server.ClientLogout(ClientOnline);                ClientOnline.Close();	        }            if (Error == 0)            {                // FIRST_LOGIN		0. Tặng lần đầu đăng nhập (50.000)                if (UserInfo.FirstLogin == 1)                {                    CLog.LogMoney("FIRST_LOGIN", UserInfo.UserName, 0, Client.GetGold(), 0, CGlobal.Config.GoldInit);                }                        }            if (Error == 0)            {                if (UserInfo.Active == 0)                {                    Error = 3;                }            }            if (Error == 0)            {                if (UserInfo.Lock == 1)                {                    Error = 4;                }            }                        // Login	        if(Error == 0)	        {		        // Login		        CGlobal.Server.ClientLogin(Client, UserInfo);                Client.Sex = CCommon.String2Int(dt.Rows[0]["Sex"].ToString());                Client.BirthYear = CCommon.String2Int(dt.Rows[0]["BirthYear"].ToString());                Client.CityId = CCommon.String2Int(dt.Rows[0]["CityId"].ToString());                Client.RealName = dt.Rows[0]["RealName"].ToString();                Client.Address = dt.Rows[0]["Address"].ToString();                Client.CMND = dt.Rows[0]["CMND"].ToString();                Client.Status = dt.Rows[0]["Status"].ToString();                Client.Password = dt.Rows[0]["Password"].ToString();                // Log money                CLog.LogMoney("USER_LOGIN", Client.UserName, Client.GetXu(), Client.GetGold(), 0, 0);	        }	        // Send Login Result	        CPacket p = new CPacket(CCommon.MT_LOGIN_RESULT);	        p.WriteInt(Error);	        p.WriteInt(UserInfo.UserId);	        p.WriteInt(UserInfo.AccountId);	        p.WriteInt(UserInfo.AvatarId);	        p.WriteInt(0);	        p.WriteInt(1);	        p.WriteInt(UserInfo.UnreadMail);	        p.WriteInt(0);	        p.WriteDouble(UserInfo.Gold);            for(int i = 0; i < CCommon.NUM_GOLD_BET; i++)            {		        p.WriteDouble(0);            }	        p.WriteString(UserInfo.UserName, CCommon.MAX_USERNAME_LENGTH);	        p.WriteString(CGlobal.Config.Version, CCommon.MAX_VERSION_LENGTH);            p.WriteDouble(UserInfo.Xu);            p.WriteString(UserInfo.RealName, CCommon.MAX_USERNAME_LENGTH);            p.WriteInt(UserInfo.FirstLogin);            p.WriteDouble(UserInfo.XuPay);	        Client.Send(p);            // Send Public Text            CPacket p1 = new CPacket(CCommon.MT_PUBLIC_TEXT);            p1.WriteInt(CGlobal.Config.Exchange);            p1.WriteString(CGlobal.Config.PublicText, CGlobal.Config.PublicText.Length + 1);            Client.Send(p1);        }        // Process register        public void ProcessRegister(CClient Client, CPacket Packet)        {            // Get Request            string UserName = Packet.ReadStringAt(0, CCommon.MAX_USERNAME_LENGTH);            string Password = Packet.ReadString(CCommon.MAX_PASSWORD_LENGTH);            string Password2 = Packet.ReadString(CCommon.MAX_PASSWORD_LENGTH);            // Dữ liệu trống            if (Password.Length == 0 || UserName.Length == 0)            {                return;            }            // Tên đăng nhập phải từ 5 đến 10 ký tự            if (UserName.Length < 5 || UserName.Length > 10)            {                return;            }            // Result            int Result = 0, AccountId = 0;            CGlobal.Database.GetRegisterResult(Client.ClientId, UserName, Password, Password2, ref Result, ref AccountId);            // Đăng ký thành công            if (Result == 0)            {                // Tặng quà tân thủ                CGlobal.Database.SendMail(AccountId, "admin", UserName, "Qua tang tan thu", "Xin chuc mung ban da tham gia cong dong Than Bai. He thong xin tang ban 50.000$ mien phi de choi cac tro choi. Ban co the nap them tien tai phan ngan hang");            }            // Send            CPacket p = new CPacket(CCommon.MT_REGISTER_RESULT);            p.WriteInt(Result);            p.WriteInt(AccountId);            Client.Send(p);        }        // Mua vật phẩm trong cửa hàng        public void ProcessBuyAvatar(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            // Lấy Id vật phẩm            int ItemId = Packet.ReadIntAt(0);            // Mua vật phẩm đặc biệt            if (ItemId >= 1000)            {                double GoldAdd = 0;                double XuAdd = 0;                int Result = 1;                switch (ItemId)                {                     // Tẩy nhỏ                    case 1000:                        {                            if (Client.GetXu() < 1000)                            {                                return;                            }                            Result = 0;                            XuAdd = -1000;                            int AppId = Packet.ReadInt();                            Client.AddXu(-1000);                            Client.ResetScore(AppId);                            Client.SaveXu();                        }                        break;                    // Tẩy lớn                    case 1001:                        if (Client.GetXu() < 5000)                        {                            return;                        }                        Result = 0;                        XuAdd = -5000;                        Client.AddXu(-5000);                        Client.ResetAllScore();                        Client.SaveXu();                        break;                    case 1002:                        {                            if (Client.GetXu() < 1000)                            {                                return;                            }                            Result = 0;                            XuAdd = -1000;                            Client.AddXu(-1000);                            string Message = Packet.ReadString(CCommon.MAX_MAIL_LENGTH);                            SendMailToFriend(Client, Message);                            Client.SaveXu();                        }                        break;                    case 1003:                        {                            if (Client.GetXu() < 5000)                            {                                return;                            }                            Result = 0;                            XuAdd = -5000;                            Client.AddXu(-5000);                            string Message = Packet.ReadString(CCommon.MAX_MAIL_LENGTH);                            SendMailToAll(Client, Message);                            Client.SaveXu();                        }                        break;                    case 1004:                        {                            if (Client.GetXu() < 1000)                            {                                return;                            }                            Result = 0;                            XuAdd = -1000;                            Client.AddXu(-1000);                            Client.SetExpHs(1.5, 1);                            Client.SaveXu();                        }                        break;                    case 1005:                        {                            if (Client.GetXu() < 5000)                            {                                return;                            }                            Result = 0;                            XuAdd = -5000;                            Client.AddXu(-5000);                            Client.SetExpHs(1.5, 6);                            Client.SaveXu();                        }                        break;                    case 1006:                        {                            if (Client.GetXu() < 2000)                            {                                return;                            }                            Result = 0;                            XuAdd = -2000;                            Client.AddXu(-2000);                            Client.SetExpHs(2, 1);                            Client.SaveXu();                        }                        break;                    case 1007:                        {                            if (Client.GetXu() < 6000)                            {                                return;                            }                            Result = 0;                            XuAdd = -6000;                            Client.AddXu(-6000);                            Client.SetExpHs(2, 6);                            Client.SaveXu();                        }                        break;                }                // Lưu log                CLog.LogBuyShopItem(Client.UserName, ItemId, -1, GoldAdd, XuAdd, Client.GetGold(), Client.GetXu());                // BUY_SHOP_ITEM		4. Mua vật phẩm trong cửa hàng ( Giảm )                CLog.LogMoney("BUY_SHOP_ITEM", Client.UserName, Client.GetXu(), Client.GetGold(), XuAdd, GoldAdd);                // Result                CPacket p = new CPacket(CCommon.MT_BUY_AVATAR_RESULT);                p.WriteInt(Result);                p.WriteDouble(Client.GetGold());                p.WriteDouble(Client.GetXu());                Client.Send(p);            }            // Mua vật phẩm thường            else            {                int Result = Client.BuyAvatar(ItemId, true);                if (Result == 0)                {                    Client.SaveMoney();                }                // Result                CPacket p = new CPacket(CCommon.MT_BUY_AVATAR_RESULT);                p.WriteInt(Result);                p.WriteDouble(Client.GetGold());                p.WriteDouble(Client.GetXu());                Client.Send(p);            }        }        // Gửi tin nhắn cho bạn bè        private void SendMailToFriend(CClient Client, string Message)        {            List<CUserInfo> UserList = new List<CUserInfo>();            CGlobal.Database.GetUserList(Client.AccountId, 0, -1, ref UserList);            for (int i = 0; i < UserList.Count; i++)            {                CUserInfo UserInfo = UserList[i];                CGlobal.Database.SendMail(UserInfo.AccountId, Client.UserName, UserInfo.UserName, "", Message);            }        }        // Gửi tin nhắn cho tất cả người chơi đang online        private void SendMailToAll(CClient Client, string Message)        {            for (int i = 0; i < CGlobal.Config.MaxClient; i++)            {                CClient c = CGlobal.Server.ClientList[i];                if (c.IsLogin() && !c.IsBot)                {                    CGlobal.Database.SendMail(c.AccountId, Client.UserName, c.UserName, "", Message);                                    }            }        }        // Tặng vật phẩm trong cửa hàng cho người chơi khác        public void ProcessSendAvatar(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            // Lấy thông tin            int ItemId = Packet.ReadIntAt(0);            string ReceiveName = Packet.ReadString(CCommon.MAX_USERNAME_LENGTH);            int Result = Client.SendAvatar(ItemId, ReceiveName, true);            if (Result == 0)            {                Client.SetGold(Client.GetGold());                Client.SetXu(Client.GetXu());                Client.SaveMoney();            }            // Result            CPacket p = new CPacket(CCommon.MT_SEND_AVATAR);            p.WriteInt(Result);            p.WriteDouble(Client.GetGold());            p.WriteDouble(Client.GetXu());            Client.Send(p);        }        // GamePacket        public void ProcessGamePacket(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsInTable())	        {		        return;	        }	        // Receive Game Packet	        Client.Table.GameLogic.OnReceive(Client, Packet);        }        // Xử lý mời chơi cùng        public void ProcessInvite(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsInTable())	        {		        return;	        }	        // Get Request	        int ReceiveId = Packet.ReadIntAt(0);	        int AppId = Packet.ReadInt();	        // Get Receiver Info            CClient Receiver = CGlobal.Server.GetClientByAccountId(ReceiveId);	        if(Receiver == null)	        {		        return;	        }	        if(!Receiver.IsLogin() || Receiver.IsInTable())	        {		        return;	        }	        // Send Notify	        CPacket p = new CPacket(CCommon.MT_INVITE);	        p.WriteInt(AppId);	        p.WriteInt(Client.Table.GameId);	        p.WriteDouble(Client.Table.GoldBet);	        p.WriteString(Client.UserName, CCommon.MAX_USERNAME_LENGTH);	        Receiver.Send(p);        }        public void ProcessGiftDailyInfo(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsLogin() || Client.IsInTable())	        {		        return;	        }	        // Send	        CPacket p = new CPacket(CCommon.MT_GIFT_DAILY_INFO);	        p.WriteInt(Client.ReceiveGift);	        p.WriteInt(Client.DayCount);	        Client.Send(p);        }        public void ProcessGiftTimeInfo(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsLogin() || Client.IsInTable())	        {		        return;	        }	        // Get	        double TimeCountDown = 0;            //CGlobal.Database.GetGiftTime(Client.AccountId, ref ReceiveCount, ref TimeCountDown);	        // Send	        CPacket p = new CPacket(CCommon.MT_GIFT_TIME_INFO);	        p.WriteInt(Client.GiftCount);	        p.WriteDouble(TimeCountDown);	        Client.Send(p);        }        public void ProcessReceiveGiftDaily(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsLogin() || Client.IsInTable())	        {		        return;	        }            // - Điều kiện nhận quà: tài khoản còn dưới 20.000$.            if (Client.GetGold() >= 20000)            {                return;            }	        // Get	        int Result = 0;            double GoldAdd = 0;            if (Client.ReceiveGift == 1)            {                Result = 1;            }            else            {                //double[] GoldRand = { 3000, 5000, 7000, 10000 };                //switch (TableUser.DayCount)                //{                //    case 1:                //        GoldAdd = 500;                //        break;                //    case 2:                //        GoldAdd = 10000;                //        break;                //    case 3:                //        GoldAdd = 15000;                //        break;                //    case 4:                //        GoldAdd = 20000;                //        break;                //    case 5:                //        GoldAdd = CCommon.RandomNumber(25000, 100000);                //        break;                //}                GoldAdd = 10000;                Client.ReceiveGift = 1;                Client.AddGold(GoldAdd, "Giang ho nghia hiep");                Client.SaveGold();                // EVENT_BONUS		13.Sự kiện giang hồ hiệp nghĩa ( + với số tiền hiện còn thành 10k )                CLog.LogMoney("EVENT_BONUS", Client.UserName, Client.GetXu(), Client.GetGold(), 0, GoldAdd);            }	        // Send	        CPacket p = new CPacket(CCommon.MT_RECEIVE_GIFT_DAILY_RESULT);	        p.WriteInt(Result);	        p.WriteDouble(Client.GetGold());            p.WriteDouble(GoldAdd);	        Client.Send(p);        }        public void ProcessReceiveGiftTime(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsLogin() || Client.IsInTable())	        {		        return;	        }	        // Get	        int Result = 0;            double TimeCountDown = 0;            double GoldAdd = 0;            if (Client.GiftCount >= 3)            {                Result = 1;            }            else            {                Client.GiftCount++;                GoldAdd = 0;                switch (Client.GiftCount)                {                    case 1:                        GoldAdd = 20000;                        break;                    case 2:                        GoldAdd = 30000;                        break;                }                Client.AddGold(GoldAdd, "Tang qua");                Client.SaveGold();                // EVENT_ONLINE		11.Sự kiện online nhận quà ( + 20 và 30k )                CLog.LogMoney("EVENT_ONLINE", Client.UserName, Client.GetXu(), Client.GetGold(), 0, GoldAdd);            }	        // Send	        CPacket p = new CPacket(CCommon.MT_RECEIVE_GIFT_TIME_RESULT);	        p.WriteInt(Result);	        p.WriteInt(Client.GiftCount);	        p.WriteDouble(TimeCountDown);	        p.WriteDouble(Client.GetGold());	        p.WriteDouble(GoldAdd);	        Client.Send(p);        }        // Channel Info        public void ProcessChannelInfo(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }                        // Get	        int AppId = Packet.ReadIntAt(0);	        // Send	        CPacket p = new CPacket(CCommon.MT_SUB_CHANNEL_INFO);            p.WriteInt(CGlobal.Config.MaxRoom / CGlobal.Config.NumGame);            p.WriteInt(CGlobal.Config.MaxClientInRoom);            for (int i = 0; i < CGlobal.Config.MaxRoom; i++)            {                CChannel Channel = CGlobal.Server.ChannelList[i];                if (Channel.AppId == AppId)                {                    p.WriteInt(Channel.ChannelId);                    p.WriteInt(Channel.ChannelType);                    p.WriteInt(Channel.NumClient);                    p.WriteDouble(Channel.MinGoldBet);                    p.WriteDouble(Channel.MaxGoldBet);                    p.WriteDouble(Channel.MinToPlay);                }            }	        Client.Send(p);        }        // Lobby Info        public void ProcessLobbyInfo(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsLogin() || Client.IsInTable())	        {		        return;	        }        		        // Get	        int AppId = Packet.ReadIntAt(0);	        int ChannelId = Packet.ReadInt();	        int Request = Packet.ReadInt();	        // Check Sub channel            CChannel Channel = CGlobal.Server.GetChannel(ChannelId);	        if(Channel == null)	        {		        return;	        }	        // Join	        if(Client.IsInChannel())	        {		        Client.Channel.ClientLeft();		        Client.LeftChannel();	        }	        Channel.ClientJoin();	        Client.JoinChannel(Channel);	        // Phòng chờ đầy            if(!Channel.CanClientJoin())	        {                return;	        }            // Gửi danh sách bàn            SendLobbyInfo(Client);        }        public void ProcessAcceptAddFriend(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin())            {                return;            }            // Get Request            int Add = Packet.ReadIntAt(0);            string UserName = Packet.ReadString(CCommon.MAX_USERNAME_LENGTH);            int FriendId = 0;            int Result = CGlobal.Database.GetAddFriendResult(Client.AccountId, UserName, Add, ref FriendId);            // Notify Add Friend            if (Result == 0 && Add == 1 && CGlobal.Database.CheckFriendListStatus(FriendId, Client.AccountId) == 0)            {                CClient Friend = CGlobal.Server.GetClientByAccountId(FriendId);                if (Friend != null)                {                    int Friend2Id = 0;                    int Result2 = CGlobal.Database.GetAddFriendResult(Friend.AccountId, Client.UserName, Add, ref Friend2Id);                    CPacket p1 = new CPacket(CCommon.MT_ADD_FRIEND_RESULT);                    p1.WriteInt(Add);                    p1.WriteInt(Result2);                    Friend.Send(p1);                    // Update Status                    CGlobal.Database.ExecuteQuery("UPDATE FriendList SET Status=1 WHERE UserId1=" + Client.AccountId + " AND UserId2=" + FriendId);                }            }            // Send            CPacket p = new CPacket(CCommon.MT_ADD_FRIEND_RESULT);            p.WriteInt(Add);            p.WriteInt(Result);            Client.Send(p);        }        // Add friend        public void ProcessAddFriend(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsLogin())	        {		        return;	        }	        // Get Request	        int Add = Packet.ReadIntAt(0);            string UserName = Packet.ReadString(CCommon.MAX_USERNAME_LENGTH);	        // Xóa            if (Add != 1)            {                int FriendId = 0;                int Result = CGlobal.Database.GetAddFriendResult(Client.AccountId, UserName, Add, ref FriendId);                // Notify Add Friend                if (Result == 0 && Add == 1 && CGlobal.Database.CheckFriendListStatus(FriendId, Client.AccountId) == 0)                {                    CClient Friend = CGlobal.Server.GetClientByAccountId(FriendId);                    if (Friend != null)                    {                        // Send Notify                        CPacket p1 = new CPacket(CCommon.MT_NOTIFY_ADD_FRIEND);                        p1.WriteString(Client.UserName, CCommon.MAX_USERNAME_LENGTH);                        Friend.Send(p1);                        // Update Status                        CGlobal.Database.ExecuteQuery("UPDATE FriendList SET Status=1 WHERE UserId1=" + Client.AccountId + " AND UserId2=" + FriendId);                    }                }                // Send                CPacket p = new CPacket(CCommon.MT_ADD_FRIEND_RESULT);                p.WriteInt(Add);                p.WriteInt(Result);                Client.Send(p);            }            // Thêm bạn            else            {                CClient FriendClient = CGlobal.Server.GetClientByUserName(UserName);                if (FriendClient == null)                {                    SendNotifyError(Client, CCommon.ERROR_USER_NOT_ONLINE);                    return;                }                if (FriendClient.Table != Client.Table)                {                    return;                }                CPacket p1 = new CPacket(CCommon.MT_ACCEPT_ADD_FRIEND);                p1.WriteString(Client.UserName, CCommon.MAX_USERNAME_LENGTH);                FriendClient.Send(p1);            }        }        // Mail list        public void ProcessMailList(CClient Client, CPacket Packet)        {            // Check Client            if(!Client.IsLogin() || Client.IsInTable())            {                return;            }            // List            List<CMailInfo> MailList = new List<CMailInfo>();            // Process            int Page = Packet.ReadIntAt(0);            if (Page <= 0)            {                Page = 1;            }            CGlobal.Database.GetMailList(Client.AccountId, ref MailList, Page);            // Send            CPacket p = new CPacket(CCommon.MT_MAIL_LIST);            p.WriteInt(MailList.Count);            for(int i = 0; i < MailList.Count; i ++)            {                p.WriteInt(MailList[i].MailDbId);                p.WriteInt(MailList[i].Status);                p.WriteInt(MailList[i].Day);                p.WriteInt(MailList[i].Month);                p.WriteInt(MailList[i].Year);                p.WriteInt(MailList[i].Hour);                p.WriteInt(MailList[i].Min);                p.WriteInt(MailList[i].Sec);                p.WriteString(MailList[i].FromUserName, CCommon.MAX_USERNAME_LENGTH);                p.WriteString(MailList[i].Title, CCommon.MAX_TITLE_LENGTH);            }            Client.Send(p);        }        // Mail content        public void ProcessMailContent(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            // Get            int MailDbId = Packet.ReadIntAt(0);            DataTable dt = CSQL.GetData("SELECT * FROM Mail WHERE Id=" + MailDbId);            if (dt.Rows.Count == 0)            {                return;            }            string Time = dt.Rows[0]["Time"].ToString();            DateTime d = new DateTime();            DateTime.TryParse(Time, out d);            // Result            CPacket p = new CPacket(CCommon.MT_MAIL_CONTENT);            p.WriteInt(d.Day);            p.WriteInt(d.Month);            p.WriteInt(d.Year);            p.WriteInt(d.Hour);            p.WriteInt(d.Minute);            p.WriteInt(d.Second);            p.WriteString(dt.Rows[0]["FromUserName"].ToString(), CCommon.MAX_USERNAME_LENGTH);            p.WriteString(dt.Rows[0]["Title"].ToString(), CCommon.MAX_TITLE_LENGTH);            p.WriteString(dt.Rows[0]["Content"].ToString(), CCommon.MAX_MAIL_LENGTH);            Client.Send(p);        }        // Send mail        public void ProcessSendMail(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsLogin() || Client.IsInTable())	        {		        return;	        }	        // Get            string UserName = Packet.ReadStringAt(0, CCommon.MAX_USERNAME_LENGTH);            string Title = Packet.ReadString(CCommon.MAX_TITLE_LENGTH);	        string Content = Packet.ReadString(CCommon.MAX_MAIL_LENGTH);	        // Result            int Result = CGlobal.Database.SendMail(Client.AccountId, Client.UserName, UserName, Title, Content);	        // Result	        CPacket p = new CPacket(CCommon.MT_SEND_MAIL_RESULT);	        p.WriteInt(Result);	        Client.Send(p);        }        // Delete mail        public void ProcessDeleteMail(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsLogin() || Client.IsInTable())	        {		        return;	        }	        // Get	        int MailId = Packet.ReadIntAt(0);	        // Result            int Result = CGlobal.Database.DeleteMail(MailId);        }        // Create Game        public void ProcessCreateGame(CClient Client, CPacket Packet)        {	        // Người chơi phải ở lobby mới được tạo bàn	        if(!Client.IsLogin() || Client.IsInTable())	        {		        return;	        }	        // Lấy thông tin bàn chơi	        int AppId = Packet.ReadIntAt(0);	        int TableId = Packet.ReadInt();	        int ChannelId = Packet.ReadInt();	        int GameMode = Packet.ReadInt();	        double GoldBet = Packet.ReadDouble();            CTable Table = CGlobal.Server.GetTable(TableId);	        if(Table == null)	        {		        return;	        }	        // Bàn chơi đã có người	        if(Table.GameStage != CCommon.GS_WAITING_ROOM || Table.GetNumClient() > 0)	        {                CGlobal.PacketHandler.SendNotifyError(Client, CCommon.ERROR_TABLE_HAS_CLIENT);                SendLobbyInfo(Client);                return;	        }	        // Thiếu tiền đặt cược            if (Client.GetGold() < Table.GoldBet * CGlobal.Config.MinToPlay)            {                CGlobal.PacketHandler.SendNotifyError(Client, CCommon.ERROR_NOT_ENOUGH_BET_MONEY);                return;            }	        // Tạo bàn chơi	        Table.CreateGame(GoldBet);	        int Chair = Table.AddClient(Client);	        Client.JoinTable(Table);	        Table.SetOwner(Client);	        Client.Chair = Chair;	        Client.IsViewer = false;            CUserGame UserGame = Client.GetUserGame(Table.AppId);            if (UserGame != null)            {                Client.Level = UserGame.Level;            }	        // Send Result	        CPacket p = new CPacket(CCommon.MT_CREATE_GAME_RESULT);	        p.WriteInt(0);	        p.WriteInt(AppId);	        p.WriteInt(Table.Channel.ChannelId);            p.WriteInt(Table.GameId);	        p.WriteInt(GameMode);	        p.WriteDouble(Table.GoldBet);            p.WriteInt(Table.ChickenBet);            p.WriteInt(Table.NumChicken);	        Client.Send(p);	        // Send Client Info	        Table.SendClientJoin(Client);            // Gửi cập nhật emotion vip            SendEmotionList(Client);        }        // Join Game        public void ProcessJoinGame(CClient Client, CPacket Packet)        {	        // Người chơi phải ở lobby mới đc vào	        if(!Client.IsLogin() || Client.IsInTable())	        {		        return;	        }	        // Lấy thông tin request	        int Error = 0;	        int TableId = Packet.ReadIntAt(0);	        string Password = Packet.ReadString(CCommon.MAX_GAME_PASSWORD_LENGTH);                        CTable Table = CGlobal.Server.GetTable(TableId);	        if(Table == null)	        {		        return;	        }            // 2 người cùng IP ko thể vào 1 bàn            if (Table.CheckSameIP(Client))            {                return;            }            // Nếu phòng đang chơi, người vào phòng là người xem game	        Client.IsViewer = Table.IsPlaying();	        // Bàn chơi đã đầy	        if(!Table.CanAddClient(Client))	        {                SendNotifyError(Client, CCommon.ERROR_TABLE_IS_FULL);                return;	        }            if (!Table.GameLogic.CanJoinTable(Client))            {                return;            }            // Không đủ tiền cược để vào bàn	        if (Client.GetGold() < Table.GoldBet * CGlobal.Config.MinToPlay)            {                SendNotifyError(Client, CCommon.ERROR_NOT_ENOUGH_BET_MONEY);                return;	        }	        // Send Result	        CPacket p = new CPacket(CCommon.MT_JOIN_GAME_RESULT);	        p.WriteInt(0);	        p.WriteInt(Table.AppId);	        p.WriteInt(Table.Channel.ChannelId);            p.WriteInt(Table.GameId);	        p.WriteInt(1);	        p.WriteInt(Table.GameStage);	        p.WriteInt(0);	        p.WriteDouble(Table.GoldBet);            p.WriteInt(Table.ChickenBet);            p.WriteInt(Table.NumChicken);	        Client.Send(p);	        // Add Client	        if(Error == 0)	        {                if (Client.Channel == null)                {                    Table.Channel.ClientJoin();                    Client.JoinChannel(Table.Channel);                }                else                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              {                    if (Table.Channel != Client.Channel)                    {                        Client.Channel.ClientLeft();                        Client.LeftChannel();                        Table.Channel.ClientJoin();                        Client.JoinChannel(Table.Channel);                    }                }		        int Chair = Table.AddClient(Client);		        Client.Chair = Chair;		        Client.JoinTable(Table);                if (Table.GetNumClient() == 1)                {                    Table.SetOwner(Client);                }                CUserGame UserGame = Client.GetUserGame(Table.AppId);                if (UserGame != null)                {                    Client.Level = UserGame.Level;                }                Table.SendClientJoin(Client);		        // Send Viewer Data		        if(Client.IsViewer)		        {			        Table.GameLogic.SendViewerData(Client);		        }	        }            // Gửi cập nhật emotion vip            SendEmotionList(Client);        }        // Auto Join Game        public void ProcessAutoJoinGame(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsLogin() || Client.IsInTable())	        {		        return;	        }	        // Get Channel Info	        int ChannelId = Packet.ReadIntAt(0);            CChannel Channel = CGlobal.Server.GetChannel(ChannelId);	        if(Channel == null)	        {		        return;	        }            CTable Table = CGlobal.Server.FindAvailTable(Channel, Client.GetGold());	        if(Table == null)	        {		        CPacket Packet1 = new CPacket(CCommon.MT_NOTIFY_ERROR);		        Packet1.WriteInt(1);		        Client.Send(Packet1);		        return;	        }	        if(Table.GetNumClient() > 0)	        {		        CPacket p = new CPacket(CCommon.MT_JOIN_GAME_RESULT);		        p.WriteInt(0);		        p.WriteInt(Table.AppId);		        p.WriteInt(Table.Channel.ChannelId);                p.WriteInt(Table.GameId);		        p.WriteInt(1);		        p.WriteInt(Table.GameStage);		        p.WriteInt(0);		        p.WriteDouble(Table.GoldBet);		        Client.Send(p);		        int Chair = Table.AddClient(Client);		        Client.Chair = Chair;		        Client.JoinTable(Table);	        }	        else	        {		        // Create Game		        double GoldBet = Table.GetMinGoldBet();		        Table.CreateGame(GoldBet);		        int Chair = Table.AddClient(Client);		        Client.JoinTable(Table);		        Table.SetOwner(Client);		        Client.Chair = Chair;                CUserGame UserGame = Client.GetUserGame(Table.AppId);                if (UserGame != null)                {                    Client.Level = UserGame.Level;                }		        // Send Result		        CPacket p = new CPacket(CCommon.MT_CREATE_GAME_RESULT);		        p.WriteInt(0);		        p.WriteInt(Table.AppId);		        p.WriteInt(Table.Channel.ChannelId);                p.WriteInt(Table.GameId);                p.WriteInt(0);		        p.WriteDouble(GoldBet);		        Client.Send(p);	        }	        // Send Client Info	        Table.SendClientJoin(Client);            // Gửi cập nhật emotion vip            SendEmotionList(Client);        }        public void SendEmotionList(CClient Client)        {            // Gửi kết quả            CPacket p = new CPacket(CCommon.MT_EMOTION_LIST);            p.WriteInt(Client.EmotionList.Count);            for (int i = 0; i < Client.EmotionList.Count; i++)            {                int ImageId = Client.EmotionList[i];                p.WriteInt(ImageId);            }            Client.Send(p);        }        // Quit Game        public void ProcessQuitGame(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsInTable())	        {		        return;	        }            // Send Notify            Client.Table.SendClientLeft(Client, false);            // Remove Client            Client.Table.RemoveClient(Client);            Client.LeftTable();            // Send Lobby Info            SendLobbyInfo(Client);        }        // Send Lobby Info        public void SendLobbyInfo(CClient Client)        {	        int Error = 0;	        CPacket p1 = new CPacket(CCommon.MT_LOBBY_INFO);	        p1.WriteInt(Error);	        p1.WriteInt(Client.Channel.ChannelId);	        p1.WriteInt(CGlobal.Config.MaxTableInRoom);	        p1.WriteInt(0);	        for(int i = 0; i < CGlobal.Config.MaxTable; i ++)	        {                CTable Table = CGlobal.Server.GetTable(i);		        if(Table.Channel == Client.Channel)		        {			        p1.WriteInt(Table.GameId);			        p1.WriteByte(Table.GetNumClient());                    p1.WriteInt((int)Table.GoldBet);                    p1.WriteInt((int)Table.ChickenBet);		        }	        }            p1.WriteInt(CGlobal.Server.ClientCount);            p1.WriteInt(CGlobal.Config.MaxRoom);            for (int i = 0; i < CGlobal.Config.MaxRoom; i++)            {                CChannel Channel = CGlobal.Server.ChannelList[i];                p1.WriteInt(Channel.ChannelId);                p1.WriteInt(Channel.NumClient);            }            p1.WriteDouble(Client.GetGold());            Client.Send(p1);	        }        // Basic info        public void ProcessUserBasicInfo(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            CPacket p = new CPacket(CCommon.MT_USER_BASIC_INFO);            p.WriteInt(Client.AvatarId);            p.WriteInt(Client.Sex);            p.WriteInt(Client.BirthYear);            p.WriteInt(Client.CityId);            p.WriteInt(0);            p.WriteInt(1);            p.WriteDouble(Client.GetGold());            p.WriteString(Client.RealName, CCommon.MAX_USERNAME_LENGTH);            p.WriteString(Client.Address, CCommon.MAX_ADDRESS_LENGTH);            p.WriteString(Client.CMND, CCommon.MAX_CMND_LENGTH);            p.WriteString(Client.Status, CCommon.MAX_STATUS_LENGTH);            Client.Send(p);        }        // Update basic info        public void ProcessUpdateUserBasicInfo(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            Client.Sex = Packet.ReadIntAt(0);            Client.BirthYear = Packet.ReadInt();            Client.CityId = Packet.ReadInt();            Client.RealName = Packet.ReadString(CCommon.MAX_USERNAME_LENGTH);            Client.Address = Packet.ReadString(CCommon.MAX_ADDRESS_LENGTH);            Client.CMND = Packet.ReadString(CCommon.MAX_CMND_LENGTH);            Client.Status = Packet.ReadString(CCommon.MAX_STATUS_LENGTH);            CSQL.SaveData("update tableuser set Sex="+Client.Sex+                ", BirthYear="+Client.BirthYear+                ", CityId="+Client.CityId+                ", RealName='"+Client.RealName+"'"+                ", Address='" + Client.Address + "'" +                ", CMND='" + Client.CMND + "'" +                ", Status='" + Client.Status + "'" +                " where Id="+Client.AccountId);        }        // Detail info        public void ProcessUserDetailInfo(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsLogin() || Client.IsInTable())            {                return;            }            // Get            int ClientId = Packet.ReadIntAt(0);            int AppId = Packet.ReadInt();            // Result            int Win = 0, Lost = 0, Quit = 0, Level = 1;            CUserGame UserGame = Client.GetUserGame(AppId);            if (UserGame != null)            {                Win = UserGame.Win;                Lost = UserGame.Lost;                Quit = UserGame.Quit;                Level = UserGame.Level;            }            CPacket p = new CPacket(CCommon.MT_USER_DETAIL_INFO);            p.WriteInt(AppId);            p.WriteInt(Win);            p.WriteInt(Lost);            p.WriteInt(Quit);            p.WriteInt(Level);            Client.Send(p);        }        // User list        public void ProcessUserList(CClient Client, CPacket Packet)        {            // Check Client            if(!Client.IsLogin())            {                return;            }            // Get            int Type = Packet.ReadIntAt(0);            int AppId = Packet.ReadInt();            // List            List<CUserInfo> UserList = new List<CUserInfo>();            // Lấy danh sách user đang online ở lobby            if((Type == -1 || Type == -2 || Type == -3) && AppId == -1)            {                for (int i = 0; i < CGlobal.Config.MaxClient; i++)                {                    CClient c = CGlobal.Server.ClientList[i];                    if (c.IsLogin())                    {                        if (Type == -2 &&                            CGlobal.Database.CheckFriendListStatus(Client.AccountId, c.AccountId) == 0 &&                             c.IsInTable())                        {                            continue;                        }                        if (Type == -1 && c.IsInTable())                        {                            continue;                        }                        CUserInfo User = new CUserInfo();                        User.AvatarId = c.AvatarId;                        User.UserId = c.AccountId;                        User.Gold = c.GetGold();                        User.UserName = c.UserName;                        User.Status = c.Status;                        UserList.Add(User);                        if (UserList.Count >= CCommon.MAX_USER_LIST)                        {                            break;                        }                    }                }            }            else            {                switch (Type)                {                     // Lấy top người chơi vip đang online                    case 1:                        CGlobal.Server.GetTopVIP(ref UserList);                        break;                    // Lấy top cao thủ game                    case 3:                        CGlobal.Server.GetTopGame(AppId, ref UserList);                        break;                    default:                        CGlobal.Database.GetUserList(Client.AccountId, Type, AppId, ref UserList);                        break;                }            }            // Send            CPacket p = new CPacket(CCommon.MT_USER_LIST);            p.WriteInt(Type);            p.WriteInt(AppId);            p.WriteInt(UserList.Count);            for (int i = 0; i < UserList.Count; i++)            {                if (Type == 0 || Type == -2)                {                    CClient c = CGlobal.Server.GetClientByAccountId(UserList[i].UserId);                    if (c != null && Client.IsLogin())                    {                        UserList[i].Online = 1;                        UserList[i].GameId = (c.Table != null) ? c.Table.GameId : -1;                        UserList[i].ChannelId = (c.Channel != null) ? c.Channel.ChannelId : -1;                        UserList[i].AppId = (c.Channel != null) ? c.Channel.AppId : -1;                    }                    else                    {                        UserList[i].GameId = -1;                        UserList[i].Online = 0;                        UserList[i].ChannelId = -1;                        UserList[i].AppId = -1;                    }                }                p.WriteInt(UserList[i].UserId);                p.WriteInt(UserList[i].AvatarId);                p.WriteInt(UserList[i].Level);                p.WriteInt(UserList[i].Online);                p.WriteInt(UserList[i].GameId);                p.WriteInt(UserList[i].ChannelId);                p.WriteInt(UserList[i].AppId);                p.WriteDouble(UserList[i].Gold);                p.WriteString(UserList[i].UserName, CCommon.MAX_USERNAME_LENGTH);                p.WriteString(UserList[i].Status, CCommon.MAX_STATUS_LENGTH);            }            Client.Send(p);        }        // Game Chat        public void ProcessGameChat(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsInTable())	        {		        return;	        }	        // Get Request	        int ClientId = Packet.ReadIntAt(0);	        string Message = Packet.ReadString(CCommon.MAX_CHAT_MESSAGE_LENGTH);	        // Send	        if(Message.Length >= 3 &&		        Client.Table.CanAddClient(Client) &&                 Client.Table.GameStage == CCommon.GS_WAITING_ROOM)	        {		        if(Message[0] == 'b' && Message[1] == 'o' && Message[2] == 't')		        {			        string UserName = Message.Substring(4);                    CClient Bot = CGlobal.Server.AddBot(UserName);			        if(Bot != null && Client.UserName.Equals("admin"))			        {				        Client.Channel.ClientJoin();				        Bot.JoinChannel(Client.Channel);				        int Chair = Client.Table.AddClient(Bot);				        Bot.Chair = Chair;				        Bot.JoinTable(Client.Table);				        Client.Table.SendClientJoin(Bot);			        }		        }		        else if (Message[0] == 'd' && Message[1] == 'e' && Message[2] == 'l')                {                    CClient Bot = Client.Table.GetBot();                    if (Bot != null && Client.UserName.Equals("admin"))                    {                        CGlobal.Server.RemoveBot(Bot);                    }                }                else                {                    Client.Table.SendAll(Packet);                }	        }	        else	        {		        Client.Table.SendAll(Packet);	        }        }        // Kick        public void ProcessKick(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsInTable())	        {		        return;	        }	        // Is not owner	        if(Client != Client.Table.Owner)	        {		        return;	        }	        // Check Game Stage	        if(Client.Table.GameStage != CCommon.GS_WAITING_ROOM)	        {		        return;	        }	        int KickedId = Packet.ReadIntAt(0);            CClient Kicked = CGlobal.Server.GetClient(KickedId);	        if(Kicked == null)	        {		        return;	        }	        if(!Kicked.IsInTable())	        {		        return;	        }	        // Kick	        if(Kicked.IsBot)	        {                CGlobal.Server.RemoveBot(Kicked);	        }	        else	        {		        // Send Notify		        Client.Table.SendClientLeft(Kicked, false);		        // Remove Client		        Client.Table.RemoveClient(Kicked);		        Kicked.LeftTable();		        // Send Lobby Info		        SendLobbyInfo(Kicked);		        // Send Notify Kick		        // 1 : Owner kick		        // 2 : Not enough money		        CPacket p2 = new CPacket(CCommon.MT_KICK);		        p2.WriteInt(Kicked.ClientId);		        p2.WriteInt(1);		        Kicked.Send(p2);	        }        }        // Start Game        public void ProcessStartGame(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsInTable())	        {		        return;	        }	        // Is not owner	        if(Client != Client.Table.Owner)	        {		        return;	        }	        // Start Game	        if(Client.Table.GameStage == CCommon.GS_WAITING_ROOM && Client.Table.GetNumPlayer() > 1)	        {		        Client.Table.GameLogic.StartGame();	        }        }        // Set chicken        public void ProcessSetChicken(CClient Client, CPacket Packet)        {            // Check Client            if (!Client.IsInTable())            {                return;            }            // Check game stage            if (Client.Table.IsPlaying())            {                return;            }            // Client is bet            if (Client.IsChickenBet)            {                return;            }            // Lấy dữ liệu từ packet            int Value = Packet.ReadIntAt(0);            // Gửi láo            if (Value <= 0 || Value > 5)            {                return;            }            // Chưa đặt gà            if (Client.Table.ChickenBet == 0)            {                // Không đủ tiền cược                if (Client.GetGold() < Client.Table.GoldBet * CGlobal.Config.MinToPlay + Value * Client.Table.GoldBet)                {                    SendNotifyError(Client, CCommon.ERROR_NOT_ENOUGH_CHICKEN_MONEY);                    return;                }                // Đặc mức cược gà lần đầu cho bàn chơi                Client.Table.ChickenBet = Value;                Client.Table.NumChicken = 1;                // Trừ tiền, đặt vào quỹ nuôi gà                Client.GoldChicken = Client.Table.ChickenBet * Client.Table.GoldBet;                Client.AddGold(-Client.GoldChicken, "Dat ga");            }            else            {                // Không đủ tiền cược                if (Client.GetGold() < Client.Table.GoldBet * CGlobal.Config.MinToPlay + Client.Table.ChickenBet * Client.Table.NumChicken)                {                    SendNotifyError(Client, CCommon.ERROR_NOT_ENOUGH_CHICKEN_MONEY);                    return;                }                // Trừ tiền, đặt vào quỹ nuôi gà                Client.GoldChicken = Client.Table.ChickenBet * Client.Table.NumChicken * Client.Table.GoldBet;                Client.AddGold(-Client.GoldChicken, "Dat ga");            }            Client.IsChickenBet = true;            CPacket p = new CPacket(CCommon.MT_SET_CHICKEN);            p.WriteInt(Client.ClientId);            p.WriteInt(Client.Table.ChickenBet);            p.WriteInt(Client.Table.NumChicken);            p.WriteDouble(Client.GetGold());            p.WriteDouble(Client.GoldChicken);            Client.Table.SendAll(p);        }        // Send notify error        public void SendNotifyError(CClient Client, int ErrorId)        {            CPacket Packet = new CPacket(CCommon.MT_NOTIFY_ERROR);            Packet.WriteInt(ErrorId);            Client.Send(Packet);        }        // Change rule        public void ProcessChangeRule(CClient Client, CPacket Packet)        {	        // Check Client	        if(!Client.IsInTable())	        {		        return;	        }	        // Is not owner	        if(Client != Client.Table.Owner)	        {		        return;	        }	        // Check game stage	        if(Client.Table.GameStage != CCommon.GS_WAITING_ROOM)	        {		        return;	        }	        // Change Rule	        int GameMode = Packet.ReadIntAt(0);	        Packet.ReadInt();	        double GoldBet = Packet.ReadDouble();	        if(!Client.Table.CanChangeBet(Client, GoldBet))	        {		        return;	        }	        Client.Table.GoldBet = GoldBet;	        Client.Table.KickPoorClient();	        // Send	        Client.Table.SendAll(Packet);        }    }